package Hot_100;

import java.util.Scanner;

//最短无序连续子数组
public class Hot_100_581 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //初始化数组
        int n = sc.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        //调用处理函数并输出结果
        System.out.println(findUnsortedSubarray(arr));
    }

    /**
     * 求长度
     *
     * @param nums
     * @return
     */
    public static int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        int maxn = Integer.MIN_VALUE, right = -1;
        int minn = Integer.MAX_VALUE, left = -1;
        for (int i = 0; i < n; i++) {
            if (maxn > nums[i]) { //maxn:表示前一项;nums[i]:表示当前项
                right = i;//可理解为:前一项比当前项大时,该数组不为升序数组,并记录当前项.  遍历一次后,right即为最后一个使之不为升序数组的数.  left同理
            } else {
                maxn = nums[i];
            }
            if (minn < nums[n - i - 1]) {
                left = n - i - 1;
            } else {
                minn = nums[n - i - 1];
            }
        }
        return right == -1 ? 0 : right - left + 1;
    }
}
//时间复杂度: O(n)
//空间复杂度: O(1)